package com.yindian.cos.easy.security.authentication.login.social.core;

import com.yindian.cos.easy.security.authentication.login.UserDetail;
import com.yindian.cos.easy.security.authentication.login.social.SocialUserService;
import com.yindian.cos.easy.security.handler.LoginSuccessHandler;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 默认的第三方登录后置处理器
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
@Log4j2
public class DefaultPostProcessor extends AbstractPostProcessor {

    private final EasySecurityProperties easySecurityProperties;

    private final UserInfoStore userInfoStore;

    private final LoginSuccessHandler loginSuccessHandler;

    private final SocialUserService socialUserService;

    public DefaultPostProcessor(EasySecurityProperties easySecurityProperties,
                                UserInfoStore userInfoStore,
                                LoginSuccessHandler loginSuccessHandler,
                                SocialUserService socialUserService) {
        this.easySecurityProperties = easySecurityProperties;
        this.userInfoStore = userInfoStore;
        this.loginSuccessHandler = loginSuccessHandler;
        this.socialUserService = socialUserService;
    }

    @Override
    public void processorHandler(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) throws IOException {
        String provider = userInfo.getProvider();
        String openId = userInfo.getOpenId();
        String nickName = userInfo.getNickName();
        String imgUrl = userInfo.getImgUrl();
        String accessToken = userInfo.getAccessToken();
        userInfo = userInfoStore.getUserInfo(provider, openId);
        if (userInfo == null) {
            String url = easySecurityProperties.getRegisterUrl();
            url += "?provider=" + provider;
            url += "&open_id=" + openId;
            url += "&nick_name=" + URLEncoder.encode(nickName, "utf-8");
            url += "&img_url=" + imgUrl;
            url += "&access_token=" + accessToken;
            response.sendRedirect(url);
            log.debug(provider + "登录引导用户跳转至注册页面，nickName = {}，openId = {}，accessToken = {}", nickName, openId, accessToken);
        } else {
            UserDetail userDetail = socialUserService.getUserDetail(userInfo.getUserId());
            loginSuccessHandler.handler(request, response, userDetail);
        }
    }
}
